//
//  SEOrderExamineDetailViewController.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/17.
//

import UIKit

class SEOrderExamineDetailViewController: SEBaseViewController {

    // MARK: - getter
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.estimatedRowHeight = 50
            tableView.rowHeight = UITableView.automaticDimension
            tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: UIScreen.bottomSafeHeight, right: 0)
            tableView.register(SEOrderExamineDetailAddressCell.nibForCell(),
                               forCellReuseIdentifier: SEOrderExamineDetailAddressCell.reuseIdentifier())
            tableView.register(SEOrderExamineDetailPatientCell.nibForCell(),
                               forCellReuseIdentifier: SEOrderExamineDetailPatientCell.reuseIdentifier())
            tableView.register(SEOrderExamineDetailCheckItemCell.nibForCell(),
                               forCellReuseIdentifier: SEOrderExamineDetailCheckItemCell.reuseIdentifier())
            tableView.register(SEOrderExamineDetailInfoCell.nibForCell(),
                               forCellReuseIdentifier: SEOrderExamineDetailInfoCell.reuseIdentifier())
            tableView.register(SEOrderExamineDetailTextCell.nibForCell(),
                               forCellReuseIdentifier: SEOrderExamineDetailTextCell.reuseIdentifier())
            tableView.register(SECommentCell.nibForCell(), forCellReuseIdentifier: SECommentCell.reuseIdentifier())
        }
    }

    var viewModel = SEExamineDetailViewModel()
    var cancelCheckItemSuccess: (() -> Void)?
    
    init(with applyFormId: String) {
        viewModel.applyFormId = applyFormId
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        requestExamineDetail()
    }

    override func setupUI() {
        super.setupUI()
        viewModel.updateData = { [weak self] (status) in
            switch status {
            case .success:
                self?.tableView.isHidden = false
                self?.tableView.reloadData()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestExamineDetail), handle: {
                    SEHUD.showError(message: msg)
                })
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.cancelItemHandler = { [weak self] (status) in
            switch status {
            case .success:
                SEHUD.show(message: "取消成功")
                self?.cancelCheckItemSuccess?()
                self?.requestExamineDetail()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestCancelExamineItem), handle: {
                    SEHUD.showError(message: msg)
                })
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.commentHandler = { [weak self] (status) in
            switch status {
            case .success:
                SEHUD.show(message: "评价成功")
                self?.requestExamineDetail()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.submitExamineComment), handle: {
                    SEHUD.showError(message: msg)
                })
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    private func pushToExaminRecord() {
        let detailVc = SEExamineRecordViewController(with: viewModel)
        detailVc.title = "检查记录"
        navigationController?.pushViewController(detailVc, animated: true)
    }

    private func showCommentView() {
        let comment = UINib.loadViewFrom(CommentView.self)
        comment.frame = CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: UIScreen.screenHeight)
        comment.delegate = self
        comment.show()
    }

}

// MARK: - UITableViewDataSource

extension SEOrderExamineDetailViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSectionForDetail
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRowsInSectionForDetail(section: section)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEOrderExamineDetailAddressCell.reuseIdentifier()) as! SEOrderExamineDetailAddressCell
            cell.update(with: viewModel)
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEOrderExamineDetailPatientCell.reuseIdentifier()) as! SEOrderExamineDetailPatientCell
            cell.update(with: viewModel)
            return cell
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEOrderExamineDetailCheckItemCell.reuseIdentifier()) as! SEOrderExamineDetailCheckItemCell
            cell.delegate = self
            cell.update(with: viewModel.checkItem(indexPath: indexPath))
            return cell
        case 3:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEOrderExamineDetailInfoCell.reuseIdentifier()) as! SEOrderExamineDetailInfoCell
            cell.update(with: viewModel)
            return cell
        case 4:
            switch indexPath.row {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: SEOrderExamineDetailTextCell.reuseIdentifier()) as! SEOrderExamineDetailTextCell
                cell.update(at: indexPath)
                return cell
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: SECommentCell.reuseIdentifier(), for: indexPath) as! SECommentCell
                cell.updateData(score: viewModel.model.score, isComment: viewModel.model.score > 0)
                return cell
            default:
                return UITableViewCell()
            }
        default:
            return UITableViewCell()
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section == 4 else { return }
        if indexPath.row == 0 {
            pushToExaminRecord()
        }
        if indexPath.row == 1{
            guard viewModel.model.score == 0 else { return }
            showCommentView()
        }
    }
}

// MARK: - UITableViewDelegate

extension SEOrderExamineDetailViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return viewModel.heightForHeaderForDetail(section: section)
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.white
        let label = UILabel()
        label.text = "检查项目:"
        label.textColor = Asset.textLight.color
        label.font = UIFont.regular(14)
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(view.snp.centerY)
        }
        return view
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return viewModel.heightForFooterForDetail(section: section)
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        return view
    }
}

// MARK: - SEOrderExamineDetailViewController

extension SEOrderExamineDetailViewController: SEOrderExamineDetailCheckItemCellDelegate {
    func orderExamineDetailCheckItemCellCancelAction(model: SEExamineReserveCheckItem) {
        viewModel.selectedCheckItem = model
        requestCancelExamineItem()
    }
}

// MARK: - StarRatingViewDelegate

extension SEOrderExamineDetailViewController: StarRatingViewDelegate {
    func starRatingView(_ starRatingView: StarRatingView, count: Float) {
        viewModel.model.score = count
        tableView.reloadData()
        submitExamineComment()
    }
}

// MARK: - APIRequest

extension SEOrderExamineDetailViewController {
    @objc func requestExamineDetail() {
        viewModel.requestExamineDetail()
    }

    @objc func requestCancelExamineItem() {
        viewModel.requestCancelExamineItem()
    }

    @objc func submitExamineComment() {
        viewModel.submitExamineComment()
    }
}
